<script setup>
// 引入three.js
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { onMounted, ref } from 'vue'
import Stats from "three/addons/libs/stats.module.js"

// 响应式数据
const selectedDevice = ref(null);
const deviceMarkers = ref([]);
const showDeviceInfo = ref(false);
const deviceInfoPosition = ref({ x: 0, y: 0 });

// 创建3D场景对象Scene
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x87CEEB); // 天蓝色背景

// 设备数据
const devices = [
  {
    id: 1,
    name: '空调设备-01',
    type: '空调',
    status: '正常',
    position: { x: 50, y: 50, z: 50 },
    temperature: '24°C',
    power: '2.5kW'
  },
  {
    id: 2,
    name: '监控摄像头-02',
    type: '监控',
    status: '正常',
    position: { x: -80, y: 60, z: 30 },
    resolution: '4K',
    angle: '360°'
  },
  {
    id: 3,
    name: '消防设备-03',
    type: '消防',
    status: '警告',
    position: { x: 20, y: 80, z: -60 },
    pressure: '0.8MPa',
    lastCheck: '2024-01-15'
  },
  {
    id: 4,
    name: '照明设备-04',
    type: '照明',
    status: '正常',
    position: { x: -50, y: 40, z: -20 },
    brightness: '80%',
    power: '150W'
  }
];

// 创建建筑模型
const buildingGeometry = new THREE.BoxGeometry(200, 150, 100);
const buildingMaterial = new THREE.MeshLambertMaterial({
    color: 0x888888,
    transparent: true,
    opacity: 0.7
});
const building = new THREE.Mesh(buildingGeometry, buildingMaterial);
building.position.set(0, 0, 0);
scene.add(building); 
// 相机设置
const width = window.innerWidth;
const height = window.innerHeight;
const camera = new THREE.PerspectiveCamera(45, width / height, 1, 3000);
camera.position.set(300, 200, 300);
camera.lookAt(0, 0, 0);

// 创建渲染器对象
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

// 轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;

// 光照设置
const ambient = new THREE.AmbientLight(0xffffff, 0.6);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(200, 200, 100);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
scene.add(ambient);
scene.add(directionalLight);

// 鼠标射线检测
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

// 创建设备标记
function createDeviceMarker(device) {
  const group = new THREE.Group();
  
  // 创建标记点（球体）
  const markerGeometry = new THREE.SphereGeometry(3, 16, 16);
  const markerMaterial = new THREE.MeshLambertMaterial({
    color: device.status === '正常' ? 0x00ff00 : device.status === '警告' ? 0xffff00 : 0xff0000,
    emissive: device.status === '正常' ? 0x004400 : device.status === '警告' ? 0x444400 : 0x440000
  });
  const marker = new THREE.Mesh(markerGeometry, markerMaterial);
  
  // 创建发光环效果
  const ringGeometry = new THREE.RingGeometry(4, 6, 16);
  const ringMaterial = new THREE.MeshBasicMaterial({
    color: device.status === '正常' ? 0x00ff00 : device.status === '警告' ? 0xffff00 : 0xff0000,
    transparent: true,
    opacity: 0.3,
    side: THREE.DoubleSide
  });
  const ring = new THREE.Mesh(ringGeometry, ringMaterial);
  ring.rotation.x = Math.PI / 2;
  
  // 创建连接线
  const lineGeometry = new THREE.BufferGeometry().setFromPoints([
    new THREE.Vector3(0, 0, 0),
    new THREE.Vector3(0, -20, 0)
  ]);
  const lineMaterial = new THREE.LineBasicMaterial({
    color: 0xffffff,
    transparent: true,
    opacity: 0.6
  });
  const line = new THREE.Line(lineGeometry, lineMaterial);
  
  group.add(marker);
  group.add(ring);
  group.add(line);
  group.position.set(device.position.x, device.position.y, device.position.z);
  group.userData = device;
  
  scene.add(group);
  deviceMarkers.value.push(group);
  
  return group;
}

// 创建所有设备标记
function createAllDeviceMarkers() {
  devices.forEach(device => {
    createDeviceMarker(device);
  });
}

// 鼠标移动事件
function onMouseMove(event) {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  
  raycaster.setFromCamera(mouse, camera);
  const intersects = raycaster.intersectObjects(deviceMarkers.value, true);
  
  // 重置所有标记的缩放
  deviceMarkers.value.forEach(marker => {
    marker.scale.set(1, 1, 1);
  });
  
  if (intersects.length > 0) {
    const intersectedObject = intersects[0].object.parent;
    intersectedObject.scale.set(1.2, 1.2, 1.2);
    document.body.style.cursor = 'pointer';
  } else {
    document.body.style.cursor = 'default';
  }
}

// 鼠标点击事件
function onMouseClick(event) {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
  
  raycaster.setFromCamera(mouse, camera);
  const intersects = raycaster.intersectObjects(deviceMarkers.value, true);
  
  if (intersects.length > 0) {
    const device = intersects[0].object.parent.userData;
    selectedDevice.value = device;
    showDeviceInfo.value = true;
    deviceInfoPosition.value = {
      x: event.clientX,
      y: event.clientY
    };
  } else {
    showDeviceInfo.value = false;
    selectedDevice.value = null;
  }
}
defineProps({
  msg: String,
})

// 动画函数
function animate() {
  requestAnimationFrame(animate);
  
  // 更新控制器
  controls.update();
  
  // 设备标记动画效果
  deviceMarkers.value.forEach((marker, index) => {
    const time = Date.now() * 0.001;
    const ring = marker.children[1]; // 发光环
    if (ring) {
      ring.rotation.z = time + index;
      ring.material.opacity = 0.3 + Math.sin(time * 2 + index) * 0.2;
    }
  });
  
  renderer.render(scene, camera);
}

// 窗口大小调整
function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

// 关闭设备信息面板
function closeDeviceInfo() {
  showDeviceInfo.value = false;
  selectedDevice.value = null;
}

// 选择设备（从设备列表点击）
function selectDevice(device) {
  selectedDevice.value = device;
  showDeviceInfo.value = true;
  deviceInfoPosition.value = {
    x: window.innerWidth / 2,
    y: window.innerHeight / 2
  };
  
  // 将相机聚焦到设备位置
  const devicePosition = device.position;
  const targetPosition = new THREE.Vector3(
    devicePosition.x + 100,
    devicePosition.y + 50,
    devicePosition.z + 100
  );
  
  // 平滑移动相机
  const startPosition = camera.position.clone();
  const startTime = Date.now();
  const duration = 1000;
  
  function animateCamera() {
    const elapsed = Date.now() - startTime;
    const progress = Math.min(elapsed / duration, 1);
    const easeProgress = 1 - Math.pow(1 - progress, 3);
    
    camera.position.lerpVectors(startPosition, targetPosition, easeProgress);
    camera.lookAt(devicePosition.x, devicePosition.y, devicePosition.z);
    controls.target.set(devicePosition.x, devicePosition.y, devicePosition.z);
    
    if (progress < 1) {
      requestAnimationFrame(animateCamera);
    }
  }
  
  animateCamera();
}

onMounted(() => {
  // 添加渲染器到DOM
  document.getElementById('container').appendChild(renderer.domElement);
  
  // 创建设备标记
  createAllDeviceMarkers();
  
  // 添加事件监听器
  window.addEventListener('resize', onWindowResize);
  renderer.domElement.addEventListener('mousemove', onMouseMove);
  renderer.domElement.addEventListener('click', onMouseClick);
  
  // 开始动画循环
  animate();
});
</script>

<template>
  <div class="scene-container">
    <div id="container"></div>
    
    <!-- 设备信息面板 -->
    <div 
      v-if="showDeviceInfo && selectedDevice" 
      class="device-info-panel"
      :style="{
        left: deviceInfoPosition.x + 'px',
        top: deviceInfoPosition.y + 'px'
      }"
    >
      <div class="device-info-header">
        <h3>{{ selectedDevice.name }}</h3>
        <button @click="closeDeviceInfo" class="close-btn">×</button>
      </div>
      <div class="device-info-content">
        <div class="info-row">
          <span class="label">设备类型:</span>
          <span class="value">{{ selectedDevice.type }}</span>
        </div>
        <div class="info-row">
          <span class="label">运行状态:</span>
          <span 
            class="value status"
            :class="{
              'status-normal': selectedDevice.status === '正常',
              'status-warning': selectedDevice.status === '警告',
              'status-error': selectedDevice.status === '故障'
            }"
          >
            {{ selectedDevice.status }}
          </span>
        </div>
        
        <!-- 根据设备类型显示不同的参数 -->
        <template v-if="selectedDevice.type === '空调'">
          <div class="info-row">
            <span class="label">温度:</span>
            <span class="value">{{ selectedDevice.temperature }}</span>
          </div>
          <div class="info-row">
            <span class="label">功率:</span>
            <span class="value">{{ selectedDevice.power }}</span>
          </div>
        </template>
        
        <template v-if="selectedDevice.type === '监控'">
          <div class="info-row">
            <span class="label">分辨率:</span>
            <span class="value">{{ selectedDevice.resolution }}</span>
          </div>
          <div class="info-row">
            <span class="label">视角:</span>
            <span class="value">{{ selectedDevice.angle }}</span>
          </div>
        </template>
        
        <template v-if="selectedDevice.type === '消防'">
          <div class="info-row">
            <span class="label">压力:</span>
            <span class="value">{{ selectedDevice.pressure }}</span>
          </div>
          <div class="info-row">
            <span class="label">最后检查:</span>
            <span class="value">{{ selectedDevice.lastCheck }}</span>
          </div>
        </template>
        
        <template v-if="selectedDevice.type === '照明'">
          <div class="info-row">
            <span class="label">亮度:</span>
            <span class="value">{{ selectedDevice.brightness }}</span>
          </div>
          <div class="info-row">
            <span class="label">功率:</span>
            <span class="value">{{ selectedDevice.power }}</span>
          </div>
        </template>
      </div>
    </div>
    
    <!-- 设备列表面板 -->
    <div class="device-list-panel">
      <h3>设备列表</h3>
      <div class="device-list">
        <div 
          v-for="device in devices" 
          :key="device.id"
          class="device-item"
          :class="{ 'selected': selectedDevice && selectedDevice.id === device.id }"
          @click="selectDevice(device)"
        >
          <div class="device-icon" :class="`icon-${device.type}`"></div>
          <div class="device-details">
            <div class="device-name">{{ device.name }}</div>
            <div 
              class="device-status"
              :class="{
                'status-normal': device.status === '正常',
                'status-warning': device.status === '警告',
                'status-error': device.status === '故障'
              }"
            >
              {{ device.status }}
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 操作说明 -->
    <div class="instructions">
      <p>💡 点击3D场景中的设备标记查看详细信息</p>
      <p>🖱️ 鼠标拖拽旋转视角，滚轮缩放</p>
    </div>
  </div>
</template>

<style scoped>
.scene-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #000;
}

#container {
  width: 100%;
  height: 100%;
}

/* 设备信息面板样式 */
.device-info-panel {
  position: fixed;
  background: rgba(0, 0, 0, 0.9);
  border: 2px solid #00d4ff;
  border-radius: 8px;
  padding: 0;
  min-width: 280px;
  max-width: 350px;
  z-index: 1000;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 212, 255, 0.3);
  transform: translate(-50%, -100%);
  margin-top: -10px;
}

.device-info-header {
  background: linear-gradient(135deg, #00d4ff, #0099cc);
  padding: 12px 16px;
  border-radius: 6px 6px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.device-info-header h3 {
  margin: 0;
  color: white;
  font-size: 16px;
  font-weight: bold;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.device-info-content {
  padding: 16px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  align-items: center;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  color: #ccc;
  font-size: 14px;
}

.value {
  color: white;
  font-size: 14px;
  font-weight: bold;
}

.status-normal {
  color: #00ff00;
}

.status-warning {
  color: #ffff00;
}

.status-error {
  color: #ff0000;
}

/* 设备列表面板样式 */
.device-list-panel {
  position: fixed;
  top: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.8);
  border: 1px solid #00d4ff;
  border-radius: 8px;
  padding: 16px;
  min-width: 250px;
  max-height: 400px;
  overflow-y: auto;
  backdrop-filter: blur(10px);
  z-index: 999;
}

.device-list-panel h3 {
  margin: 0 0 16px 0;
  color: #00d4ff;
  font-size: 16px;
  text-align: center;
}

.device-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.device-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.device-item:hover {
  background: rgba(0, 212, 255, 0.1);
  border-color: #00d4ff;
}

.device-item.selected {
  background: rgba(0, 212, 255, 0.2);
  border-color: #00d4ff;
}

.device-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.icon-空调 {
  background: linear-gradient(135deg, #4CAF50, #45a049);
}

.icon-监控 {
  background: linear-gradient(135deg, #2196F3, #1976D2);
}

.icon-消防 {
  background: linear-gradient(135deg, #FF5722, #D84315);
}

.icon-照明 {
  background: linear-gradient(135deg, #FFC107, #F57C00);
}

.device-details {
  flex: 1;
}

.device-name {
  color: white;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 4px;
}

.device-status {
  font-size: 12px;
}

/* 操作说明样式 */
.instructions {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.8);
  border: 1px solid #00d4ff;
  border-radius: 8px;
  padding: 12px 16px;
  backdrop-filter: blur(10px);
  z-index: 999;
}

.instructions p {
  margin: 4px 0;
  color: #ccc;
  font-size: 12px;
}

/* 滚动条样式 */
.device-list-panel::-webkit-scrollbar {
  width: 6px;
}

.device-list-panel::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.device-list-panel::-webkit-scrollbar-thumb {
  background: #00d4ff;
  border-radius: 3px;
}

.device-list-panel::-webkit-scrollbar-thumb:hover {
  background: #0099cc;
}
</style>
